<template>
  <div class="upload">
    <div @click="showActionSheet" class="upload-file">
      <span>{{ title }}</span>
      <img class="upl_img" alt src="@/assets/img/fujian.png" />
    </div>

    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      v-if="uplaodShow"
      @change="handleFileChange"
    />

    <van-action-sheet
      v-model="show"
      cancel-text="取消"
      :actions="actions"
      @select="onSelect"
    />
    <take-photo-pic v-if="showCamera" @closeCamera="showCamera=false" @getImg="getImg"></take-photo-pic>
  </div>
</template>

<script>
import { getAction, uploadAction } from "@/api/manage";
import { apiBaseUrlDownload } from "@/utils/request";
import { ImagePreview } from "vant";
import takePhotoPic from "@/components/takePhotoPic.vue";

export default {
  props: {
    id: String,
    fileUrl: Array,
    type: Number,
    isDone: Boolean,
    title: {
      type: String,
      default: "附件",
    },
    fileType: {
      type: String,
      default: "",
    }, //定义图标样式不传
    fileIds: {
      type: String,
      default: "",
    }, //父子组件需要传递的值
    titleName: {
      type: String,
      default: "附件",
    },
    maxCount: {
      type: Number,
      default: 5,
    }, //最大上传数量
    multiple: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域 //开启多选
    iconType: {
      type: String,
      default: "",
    }, //定义上传组件图标 空时默认  换图标自己在slot里加
    showUpload: {
      type: Boolean,
      default: true,
    }, //是否展示上传区域
  },
  components: {takePhotoPic},
  data() {
    return {
      selectedPhoto: "",
      photoList: [],
      show: false,
      showCamera: false,
      uplaodShow: true,
      actions: [
        { name: "拍照", color: '#3478f7' },
        { name: "从相册中选择", color: '#3478f7' },
      ],
      filePreviewShow: false,
      uri: "",
      fileList: [],
    };
  },
  watch: {
    fileIds: {
      handler(newVal, oldVal) {
        if (this.showUpload == false) {
          // this.initFileList();
        } else {
          if (newVal == "") {
            this.fileList = [];
          } else {
            // this.initFileList();
          }
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    getImg(blob) {
      this.showCamera = false
      let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      
      const files = new File([blob], 'screenshot.png', { type: 'image/jpeg' })

      formData.append("file", files);
      formData.append("biz", "temp");
      uploadAction("/sys/common/upload3", formData).then((res) => {
        if (res.success) {
          console.log(res.result);
          this.fileList = res.result
          this.fileChange();
        }
      });
    },
    showActionSheet() {
      this.show = true;
    },
    onSelect(option) {
      if (option.name === "拍照") {
        // this.takePhoto();
        this.showCamera = true
      } else if (option.name === "从相册中选择") {
        this.choosePhoto();
      } else if (option.name === "选择本地文件") {
        this.chooseFile();
      }
      this.show = false;
    },
    takePhoto() {
      // 调用摄像头拍照
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia({ video: true })
          .then((stream) => {
            // 在这里处理拍照逻辑
            console.log(stream);
            // 在获取到摄像头的视频流后，创建一个 video 元素来显示摄像头的实时画面
            const video = document.createElement("video");
            video.srcObject = stream;
            video.autoplay = true;

            // 创建一个 canvas 元素来进行截图
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");

            let that = this;

            // 当用户点击拍照时，将视频画面绘制到 canvas 上，并获取图像数据
            const takePhoto = () => {
              context.drawImage(video, 0, 0, canvas.width, canvas.height);
              canvas.toBlob(function(blob) {
                console.log(blob);
                // 在这里执行上传操作，将 blob 对象发送到服务器
                let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
                formData.append("file", blob);
                formData.append("biz", "photo.jpg");
                uploadAction("/sys/common/upload3", formData).then((res) => {
                  if (res.success) {
                    // that.fileList.push(res.result);
                    that.fileList = res.result;
                    that.fileChange();
                  }
                });
              }, "image/jpeg"); // 上传的文件类型，这里假设为 JPEG 图片

              // 停止摄像头的视频流
              stream.getTracks().forEach((track) => {
                track.stop();
              });
            };

            // 在 video 元素加载完成后，调用 takePhoto 方法进行拍照
            video.addEventListener("loadedmetadata", () => {
              takePhoto();
            });

            console.log(this.photoList);

            // 在 video 元素出错时，显示错误信息
            video.addEventListener("error", (event) => {
              console.error("摄像头打开失败:", event);
            });
          })
          .catch((error) => {
            // 处理错误
          });
      }
    },
    base64ToBinary(base64) {
      const base64Data = base64.replace(/^data:image\/jpeg;base64,/, ""); // 移除开头的 "data:image/jpeg;base64,"
      const binaryString = atob(base64Data);
      const length = binaryString.length;
      const bytes = new Uint8Array(length);

      for (let i = 0; i < length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }

      return bytes;
    },

    choosePhoto() {
      // 触发选择手机照片
      this.$refs.fileInput.click();
    },
    chooseFile() {
      // 触发选择本地文件
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = {
        file: event.target.files[0],
      };
      console.log(file, event);
      // 在这里处理选择的文件
      this.afterRead(file);
    },

    initFileList() {
      console.log("fileIds1" + this.fileIds);
      let ids = [];
      ids = this.fileIds ? this.fileIds.split(",") : [];
      this.fileList = [];
      ids.forEach((item) => {
        let params = { id: item };
        getAction("/public/pubAttachmentFile/queryById", params).then((res) => {
          if (res.success) {
            // console.log("sssss"+that_.fileList)
            let obj = res.result;
            obj.uri = "/sys/common/static/" + obj.uri;
            // console.log(obj.uri);
            this.fileList.push(obj);
          }
        });
      });
    },
    // 文件超过大小
    onOversize(file) {
      console.log(file);
      this.$toast("文件大小不能超过 10M");
    },
    /**文件上传 */
    afterRead(file) {
      let that_ = this;
      // 判断上传的文件大小是否超过要求
      const maxSizeInBytes = 10 * 1024 * 1024; // 10MB的最大文件大小（以字节为单位）
      if (file.file.size > maxSizeInBytes) {
        this.$toast("文件大小不能超过 10M");
        return;
      }
      let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      formData.append("file", file.file);
      formData.append("biz", "temp");
      this.uplaodShow = false;
      uploadAction("/sys/common/upload3", formData).then((res) => {
        if (res.success) {
          console.log(res);
          that_.fileList = res.result;
          that_.fileChange();
          this.uplaodShow = true;
        }
      });
    },
    /**文件删除 */
    beforeDelete(file, detail) {},
    /* 文件下载 */
    click_preview(item) {
      var reg = /\w*(?=\/)/;
      if (item.mediaType.match(reg)[0] == "image") {
        this.uri = apiBaseUrlDownload + "jksaas-mgt/mgt" + item.uri;
        console.log(this.uri);
        console.log(item.mediaType.match(reg)[0], item.mediaType);
        ImagePreview({
          images: [this.uri],
          startPosition: 0,
          closeable: true,
        });
      } else {
        location.href = apiBaseUrlDownload + item.uri;
      }
    },
    /* 删除文件*/
    deleteFile(index) {
      this.fileList = "";
    },
    fileChange() {
      // console.log(this.fileList.attachmentUrl);
      this.$emit("fileChange", this.fileList.attachmentUrl);
      this.fileList = "";
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .van-action-sheet {
  z-index: 999999 !important;
  // width: 90%;
  // left: 50%;
  // transform: translateX(-50%);
}
.upload-file {
  display: flex;
  justify-content: space-between;
  padding: 0.17rem;
}

.upl_img {
  width: 0.18rem;
  height: 0.18rem;
}

.upload {
  // margin-bottom: 0.1rem;
  .uploadtitle {
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.17rem;

    .title {
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
    }
  }

  .uploadcontent {
    background: #ffffff;

    .filerows {
      display: flex;
      justify-content: space-between;
      padding: 0.17rem;

      .operation {
        font-size: 0.14rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }

    .filerows2 {
      display: flex;
      justify-content: space-between;
      padding-bottom: 0.15rem;

      .operation {
        font-size: 0.14rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #1e8df5;
      }
    }
  }
}

.uplimg {
  width: 0.18rem;
  height: 0.18rem;
}

.filename {
  width: 2rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/.van-overlay {
  z-index: 999998 !important;
}
/deep/.van-popup--bottom {
  z-index: 999999 !important;
  background: none;
  bottom: 12px;
  left: 40px;
  width: 90%;
}
/deep/ .van-action-sheet__gap {
  background: none;
}
/deep/.van-popup--bottom.van-popup--round {
  border-radius: 0;
}
.van-action-sheet__content {
  border-radius: 18px;
}
.van-action-sheet__cancel {
  border-radius: 18px;
}
</style>
